package com.diandiansong.app.ui.cate;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ListView;

import com.diandiansong.app.App;
import com.diandiansong.app.R;
import com.diandiansong.app.entity.CommodityCateInfo;
import com.diandiansong.app.entity.CommodityInfoInfo;
import com.diandiansong.app.ui.Search;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.ui.index.GoodDetail;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;
import com.diandiansong.app.widgets.AddAndMinusViewInItem;
import com.diandiansong.app.widgets.SearchView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import diandiansong.library.ui.base.BaseFrag;
import diandiansong.library.ui.base.BaseListAdapter;
import diandiansong.library.ui.base.FastListFragment;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.UIHelper;
import diandiansong.library.widgets.SmartTabView;

/**
 * 分类
 */
public class Cate extends BaseFrag {

    @BindView(R.id.smarttabview)
    SmartTabView mSmarttabview;
    Unbinder unbinder;

    @BindView(R.id.search_view)
    SearchView mSearchView;

    /**
     * 大分类及其id
     */
    static Map<Integer, String> sPositions = new HashMap<>();

    public static int mBigCateIndex;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.cate_main, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mSearchView.setCusOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Search.start(getActivity());
            }
        });

        ((BaseAct) getActivity()).onLoading();
        A.commodityCate(new CCallBack<CommodityCateInfo>() {
            @Override
            public void onSuccess(CommodityCateInfo o) throws Exception {
                ((BaseAct) getActivity()).onLoaded();
                List<CommodityCateInfo.Data> data = o.getData();

                String[] titles = new String[data.size()];

                for (int i = 0; i < data.size(); i++) {
                    titles[i] = data.get(i).getCateName();
                }

                Class<? extends Fragment>[] classes = new Class[titles.length];
                Bundle[] bundles = new Bundle[titles.length];
                for (int i = 0; i < titles.length; ++i) {
                    classes[i] = CatePage.class;
                    bundles[i] = new Bundle();
                    bundles[i].putSerializable("data", data.get(i).getChild());
                    bundles[i].putInt("index", i);
                    sPositions.put(i, null);
                }

                mSmarttabview.init(
                        getActivity(),
                        getChildFragmentManager(),
                        titles, classes, bundles
                );
                mSmarttabview.mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        mBigCateIndex = position;
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }

            @Override
            public void onFailure(int code, String msg) {
                UIHelper.toast(getActivity(), msg);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static class CatePage extends BaseFrag {

        @BindView(R.id.lv_cate)
        ListView mLvCate;
        @BindView(R.id.fl_page_container)
        FrameLayout mFlPageContainer;
        Unbinder unbinder;
        BaseListAdapter mLvAdapter;

        int mIndex;
        int mCategoryPosition;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.cate_page, container, false);
            unbinder = ButterKnife.bind(this, view);
            return view;
        }

        @Override
        public void onDestroyView() {
            super.onDestroyView();
            unbinder.unbind();
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            mIndex = getArguments().getInt("index");

            mLvAdapter = new BaseListAdapter(getActivity()) {
                @Override
                protected int getLayoutRes() {
                    return R.layout.cate_item;
                }

                @Override
                public void bindView(int position, @NonNull View convertView) {
                    String item = ((CommodityCateInfo.Data.Child) getItem(position)).getCateName();
                    fastText(convertView, R.id.tv_name, item);

                    findViewById(convertView, R.id.tv_name).setActivated(mCategoryPosition == position);
                    findViewById(convertView, R.id.ll_root).setActivated(mCategoryPosition == position);
                }
            };
            mLvCate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void
                onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mCategoryPosition = position;
                    String mCategoryId = ((CommodityCateInfo.Data.Child) (mLvAdapter.getItem(position))).getCateId();
                    sPositions.put(mIndex, mCategoryId);
                    mLvAdapter.notifyDataSetChanged();
                    loadSub();
                }
            });
            mLvCate.setAdapter(mLvAdapter);
            mLvAdapter.setData(new ArrayList<CommodityCateInfo.Data.Child>() {{
                addAll((ArrayList<CommodityCateInfo.Data.Child>) (getArguments().getSerializable("data")));
            }});


            FragmentManager fm = getChildFragmentManager();
            Fragment fragment = new GoodList();
            Bundle b = new Bundle();
            b.putInt("index", mIndex);
            fragment.setArguments(b);

            fm.beginTransaction().add(mFlPageContainer.getId(), fragment).commit();

            try {
                mCategoryPosition = 0;
                String mCategoryId = ((CommodityCateInfo.Data.Child) mLvAdapter.getItem(0)).getCateId();
                sPositions.put(mIndex, mCategoryId);
                loadSub();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void loadSub() {
            GoodList.doRefreshX(true);
        }
    }

    public static class GoodList extends FastListFragment {

        int mIndex;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            EventBus.getDefault().register(this);

            mIndex = getArguments().getInt("index");
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            EventBus.getDefault().unregister(this);
        }

        boolean isOnlyShowBestSelling;
        CheckBox cbBestSell;
        CheckBox cbOrder;
        CheckBox cbFliter;

        @Override
        public void initView(View rootView) {
            super.initView(rootView);

            cbBestSell = rootView.findViewById(R.id.cb_bast_selling);
            cbBestSell.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    isOnlyShowBestSelling = cbBestSell.isChecked();
                    onRefresh();

                    if (cbBestSell.isChecked()) {
                        cbOrder.setChecked(false);
                        cbFliter.setChecked(false);
                    }
                }

            });
            cbOrder = rootView.findViewById(R.id.cb_order);
            cbOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onRefresh();
                    if (cbOrder.isChecked()) {
                        cbBestSell.setChecked(false);
                        cbFliter.setChecked(false);
                    }
                }
            });

            cbFliter = rootView.findViewById(R.id.cb_filter);
            cbFliter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cbFliter.setChecked(true);
                    cbBestSell.setChecked(false);
                    cbOrder.setChecked(false);
                    Filter.start(getActivity(), sPositions.get(mIndex));
                }
            });
        }

        @Override
        protected int getLayoutId() {
            return R.layout.cate_good_list;
        }

        @Override
        public int getItemLayoutRes() {
            return R.layout.good_item_add_minus;
        }

        @Override
        public void bindItemView(int position, @NonNull View convertView) {
            App.initGoodList(getActivity(), (CommodityInfoInfo.Data) getItem(position), position, convertView);
        }

        /**
         * 滑到底部时调用
         */
        @Override
        protected void loadMore() {
            A.commodityInfo(sPositions.get(mIndex), mPage, Filter.sBand, Filter.sKind, isOnlyShowBestSelling, new CCallBack<CommodityInfoInfo>() {
                @Override
                public void onSuccess(CommodityInfoInfo o) throws Exception {
                    List<CommodityInfoInfo.Data> data = o.getData();
                    if (mPage.equals("0")) {
                        mAdapter.setData(data);
                    } else {
                        mAdapter.addAll(data);
                    }
                    if (mAdapter.getDataSize() > 0) {
                        mPage = ((CommodityInfoInfo.Data) getLast()).getCommodityId();
                    }
                    onLoadFinishHasMore(data.size() >= Api.PAGE_SIZE);
                }

                @Override
                public void onFailure(int code, String msg) {
                    onLoadFinishNoMore();
                    toast(msg);
                }
            });
        }

        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            AddAndMinusViewInItem aamvii = view.findViewById(R.id.add_minus);
            CommodityInfoInfo.Data item = (CommodityInfoInfo.Data) getItem(position);
            GoodDetail.start(getActivity(), item.getCommodityId());
        }

        public static class Refresh {
            /**
             * 清除筛选标记
             */
            boolean clean;

            public Refresh(boolean clean) {
                this.clean = clean;
            }
        }

        public static void doRefreshX(boolean clean) {
            EventBus.getDefault().post(new Refresh(clean));
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void receiveInit(Refresh r) {
            if (mBigCateIndex == mIndex) {
                if (r.clean) {
                    Filter.sBand = null;
                    Filter.sKind = null;

                    isOnlyShowBestSelling = false;
                    cbBestSell.setChecked(false);
                    cbOrder.setChecked(false);
                    cbFliter.setChecked(false);
                }
                logger.d("band:" + Filter.sBand + " kind:" + Filter.sKind);

                if (Filter.sBand == null && Filter.sKind == null) {
                    cbFliter.setChecked(false);
                }

                onRefresh();
            }
        }
    }
}